import type { MockMethod } from 'vite-plugin-mock'
import Mock from 'mockjs'
import type { ICarResponse } from '@/types/apis/car'
import dotenv from 'dotenv'

// node环境中获取环境变量
dotenv.config({ path: '.env.development' })
const prefix = process.env.VITE_APP_BASE_API

// 响应数据中请求参数的类型
type Recordable<T = any> = Record<string, T>
interface IMockRequest {
  url: string
  body: Recordable
  query: Recordable
  headers: Recordable
}

// 生成一次 mock 数据（避免每次请求都变）
const mockCars: ICarResponse[] = Array.from({ length: 20 }, () => ({
  id: Mock.mock('@id'),
  ip: Mock.mock('@ip'),
  name: Mock.mock('@cname'),
  status: Mock.mock('@boolean'),
}))

export default [
  // 1.获取车辆列表
  {
    method: 'get',
    url: `${prefix}/mock/car`,
    response({ query }: IMockRequest) {
      // 从query中解析出params——query参数
      let { pageNum, pageSize } = query

      // 分页信息
      pageNum = Number(pageNum) || 1
      pageSize = Number(pageSize) || 10

      // 分页截取
      const start = (pageNum - 1) * pageSize
      const end = start + pageSize
      const list = mockCars.slice(start, end)

      return {
        code: 0,
        message: `获取车辆列表成功`,
        // data为any类型
        data: {
          list: list,
          total: mockCars.length,
        },
      }
    },
  },
  // 2.获取指定车辆信息
  {
    url: `${prefix}/mock/car/:id`,
    method: 'get',
    response({ url }: IMockRequest) {
      // 从url中解析出params——path参数
      const idMatch = url.match(/\/mock\/car\/([^/?]+)/)
      const id = idMatch ? idMatch[1] : null

      // const mockCar: ICarResponse = {
      //   id: id,
      //   ip: Mock.mock('@ip'),
      //   name: Mock.mock('@cname'),
      //   status: Mock.mock('@boolean'),
      // }

      // 从mockCars中找到id对应的车辆信息
      const mockCar = mockCars.find((item) => item.id === id)

      if (!mockCar) {
        return {
          code: 404,
          message: `未找到车辆 id=${id}`,
          data: null,
        }
      }

      return {
        code: 0,
        message: `获取id=${id}车辆信息成功`,
        data: mockCar,
      }
    },
  },
] satisfies MockMethod[]
